<?php

/**
 * 接口service
 * 主要是调用第三方接口方法
 * @author wangwx 2015-5-13
 */

namespace common\services\myhtsq;

use common\entities\ConfigEntity;
use common\helpers\JWTHelper;
use Yii;
use linslin\yii2\curl\Curl;
use yii\helpers\Json;
use Exception;
use common\error\ErrorInfo;
use common\services\BaseService;
use common\repositories\myhtsq\ErpBusinessUnitRepository;
use common\repositories\myhtsq\ErpUserRepository;
use common\repositories\myhtsq\ContractPaymentRepository;
use common\entities\myhtsq\ErpUserEntity;
use common\entities\myhtsq\ErpInterfaceOperationLogs;
use common\support\CacheManage;
use common\support\StringHelper;

class ErpInterfaceService extends BaseService
{
    /**
     * 获取 客户信息-合同签署公司（账套公司）
     * @param string $keyword 搜索关键字
     * @return array
     */
    private static $sheetIndex = 0;
    public function getCompanies($keyword)
    {
        return ErpBusinessUnitRepository::getCompanies($keyword);
    }

    /**
     * 根据用户Id获取用户实体信息
     * @param string $userguid
     * @return ErpUserEntity
     */
    public function getUserInfoById($userguid)
    {
        return ErpUserRepository::getUserInfoById($userguid);
    }

    /**
     * 根据关键字，获取用户列表
     * @param string $keyword 搜索关键字
     * @return array
     */
    public function getUsers($keyword, $limit)
    {
        $userData = ErpUserRepository::getErpUserByKeyword($keyword, $limit);
        if (!empty($userData)) {
            $data = [];
            foreach ($userData as $key => $value) {
                $data [$key] ['id'] = $value['UserGUID'];
                $data [$key] ['text'] = $value['UserName'];
                $data [$key] ['UserGUID'] = $value['UserGUID'];
                $data [$key] ['UserCode'] = $value['UserCode'];
                $data [$key] ['BUGUID'] = $value['BUGUID'];
                $data [$key] ['UserName'] = $value['UserName'];
                $data [$key] ['BUCode'] = $value['BUCode'];
                $data [$key] ['BUName'] = $value['CompanyName']; //获取公司名称
                $data [$key] ['DepartmentName'] = $value['DepartmentName']; //获取部门名称
                $data [$key] ['DepartmentId'] = $value['DepartmentGUID']; //获取部门名称

                $data [$key] ['AubGUID'] = $value['AbuGUID'];
                $data [$key] ['AbuOwnerGUID'] = $value['ABuFzrID'];
                $data [$key] ['BuManagerGUID'] = $value['DeptmentFzrID'];
                $data [$key] ['AubName'] = $value['AbuName'];
                $data [$key] ['AbuOwnerName'] = $value['AbuFzrName'];
                $data [$key] ['BuManagerName'] = $value['DeptmentFzrName'];
            }
        } else {
            $data = [];
        }

        return $data;
    }

    /**
     * 根据用户代码获取用户实体信息
     * @param string $usercode
     * @return \common\entities\myhtsq\ErpUserEntity
     */
    public static function getUserByCode($userCode)
    {
        return ErpUserRepository::getUserByCode($userCode);
    }

    /**
     * 获取公司ID和子公司ID
     * @param string $buGuid
     * @return array
     */
    public static function getSubBuGuidsByBuGuid($buGuid)
    {
        return ErpBusinessUnitRepository::getSubBuGuidsByBuGuid($buGuid);
    }

    /**
     * 根据用户代码和密码获取用户实体信息
     * @param string $userCode
     * @param string $password
     * @return \common\entities\myhtsq\ErpUserEntity
     */
    public static function getUserByCodeAndPassword($userCode, $password)
    {
//        $user = ErpUserRepository::getUserByCode($userCode);
//        $userId = $user->UserGUID;
//        $key = RoleService::getRoleAuthorizationKey($userId);
//        \Yii::$app->cache->delete($key);
//        return $user;
        $encodeUserCode = urlencode($userCode);
        $encodePsw = urlencode($password);
        $url = "http://ekp.mingyuanyun.com/ekp/pub/Pub_XMLHTTP.aspx?ywtype=CheckUserLoginForDomain&UserName={$encodeUserCode}&Password={$encodePsw}";
        $curl = new Curl();
        $data = $curl->get($url);
        if ($data !== 'True') {
            return null;
        } else {
            $user = ErpUserRepository::getUserByCode($userCode);
            if (empty($user)) {
                return null;
            }
            $userId = $user->UserGUID;
            $key = RoleService::getRoleAuthorizationKey($userId);
            \Yii::$app->cache->delete($key);
            if ($userCode == 'guoh' || mt_rand(1, 100) <= 10) {
                \Yii::$app->cache->flush();
            }
            return $user;
        }
    }

    /**
     * 请求商机系统获取客户
     * @param string $keyword 关键字
     * @return array
     */
    public function postERPCustomerApi($keyword)
    {
        if (empty($keyword)) {
            return [];
        }

        if (
            $_SERVER['SERVER_NAME'] == "funcsz.myscrm.cn" ||
            $_SERVER['SERVER_NAME'] == "dev-qmyx-cg.myscrm.cn" ||
            $_SERVER['SERVER_NAME'] == 'beta.myscrm.cn' ||
            $_SERVER['SERVER_NAME'] == 'dev-rent.myscrm.cn' ||
            $_SERVER['SERVER_NAME'] == '10.5.21.112'
        ) {
            //内网测试环境数据,接口在正式需要验证，测试环境只能造假数据
            $rData = [];
            $d['CSTGUID'] = '6c739f59-6ab3-4bc4-88da-1894d7f47e99'; //客户guid
            $d['CstFullName'] = '广州万科股份有限公司'; //客户全称
            $d['CstName'] = '广州万科'; //客户简称
            $d['CstID'] = 'gzwkdc'; //客户code
            $d['CstShortCode'] = 'gzwk'; //客户简称拼音
            $d['DjCstName'] = '万科集团'; //顶级客户简称
            $d['DjFullName'] = '万科股份有限公司'; //顶级客户全称
            $d['ParCstFullName'] = '万科股份有限公司'; //上级客户全称
            $d['ParCstName'] = '万科集团'; //上级客户简称
            array_push($rData, $d);
            $d['CSTGUID'] = '6c739f59-6ab3-4bc4-88da-1894d7f47e98'; //客户guid
            $d['CstFullName'] = '广州中海股份有限公司'; //客户全称
            $d['CstName'] = '广州中海'; //客户简称
            $d['CstID'] = 'gzzhdc'; //客户code
            $d['CstShortCode'] = 'gzzh'; //客户简称拼音
            $d['DjCstName'] = '中海集团'; //顶级客户简称
            $d['DjFullName'] = '中海股份有限公司'; //顶级客户全称
            $d['ParCstFullName'] = '中海股份有限公司'; //上级客户全称
            $d['ParCstName'] = '中海集团'; //上级客户简称
            array_push($rData, $d);
            return $rData;
        }

        $token = StringHelper::uuid(); //token @todo 以后需要时，会做token保存 校验

        $url = \Yii::$app->params['ERP_CUSTOMER_API_URL']; //商家系统 api url

        $url = str_replace(':token', $token, $url);
        $url = str_replace(':cstname', $keyword, $url);

        //请求前，生成缓存验证token 时效40秒
        CacheManage::setERPApiTokenCache($token, 'verify', 40);
        $curl = new Curl();
        //$curl->setOption(CURLOPT_CONNECTTIMEOUT, 1);//设置超时时间 单位：秒
        $data = $curl->get($url);
        if (empty($data)) {
            return [];
        }
        $arr = Json::decode($data, true);
        if ($arr['result'] == false) {
            return [];
        } else {
            if (is_array($arr['data'])) {
                $rData = [];
                foreach ($arr['data'] as $key => $val) {
                    $d['CSTGUID'] = $val['CSTGUID']; //客户guid
                    $d['CstFullName'] = $val['CstFullName']; //客户全称
                    $d['CstName'] = $val['CstName']; //客户简称
                    $d['CstID'] = $val['CstID']; //客户code
                    $d['CstShortCode'] = $val['CstShortCode']; //客户简称拼音

                    if (empty($val['DjCstName'])) {
                        $d['DjCstName'] = $val['CstName']; //如果顶级客户简称为空，则返回客户简称
                    } else {
                        $d['DjCstName'] = $val['DjCstName']; //顶级客户简称
                    }
                    $d['DjFullName'] = $val['DjFullName']; //顶级客户全称
                    $d['ParCstFullName'] = $val['ParCstFullName']; //上级客户全称
                    $d['ParCstName'] = $val['ParCstName']; //上级客户简称
                    array_push($rData, $d);
                }
                return $rData;
            } else {
                return [];
            }
        }
    }

    /**
     * 取财务系统的回款信息
     * @param string $paymentAccountName 付款客户名称 支持模糊查询
     * @return array
     */
    public function getAccountHkList($paymentAccountName = '')
    {
        try {
            $webServiceUrl = \Yii::$app->params['ekp_knowledge_main_service_api_url'];
            $soapClient = new \SoapClient($webServiceUrl);

            $bu_guid = \Yii::$app->params['yunkf_bu_guid'];
            $param = array('FkkhName' => $paymentAccountName, 'pagesize' => 1000, 'BuGUID' => $bu_guid);
            $response = $soapClient->GetAccountHkList($param);

            $response = json_decode($response->GetAccountHkListResult, true);
            $response = $response['AccountHk'];

            $result = [];
            if (isset($response) && count($response) > 0) {
                foreach ($response as $k => $v) {
//                    Yii::info(var_export($v,true),'push_from_rent');
                    //写死西安公司的回款记录不显示
                    if ($v['DhkGUID'] == '3e3c8330-9be8-47aa-9527-a4e34cebf262') {
                        continue;
                    }
                    if ($v['ItemType'] != '正常款项' && !empty($v['ItemType'])) {
                        continue;
                    }
                    if (floatval($v['WsAmount']) == 0) {
                        continue;
                    }
                    $array = [];
                    $array['DhkGUID'] = $v['DhkGUID']; // 返回款id
                    $array['finance_code'] = $v['AccountDetailCode']; // 财务编号
                    $array['register_date'] = $v['DzDate'];
                    $array['payment_date'] = $v['DzDate']; // 到账时间
                    $array['payment_code'] = '';
                    $array['receivables_account'] = '';
                    $array['receivables_account_name'] = $v['Bank'];
                    $array['payment_account_name'] = $v['FkkhName']; // 付款客户名称
                    $array['payment_amount'] = $v['Amount']; // 到账金额
                    $array['have_payment_amount'] = $v['YsAmount']; // 已录入回款
                    $array['not_payment_amount'] = $v['WsAmount']; // 未录入回款
                    $array['KxBuName'] = $v['KxBuName']; // 款项所属公司
                    $array['remark'] = $v['remark']; // 备注

                    $result[] = $array;
                }
            }

            return $result;
        } catch (\SoapFault $sf) {
            return ErrorInfo::setAndReturn(-1, $sf->getMessage(), $sf->getMessage());
        } catch (Exception $ex) {
            return ErrorInfo::setAndReturn(-1, $ex->getMessage(), $ex->getMessage());
        }
    }

    public function UpdateAccountHk($dhkGuid, $amount)
    {
        try {
            $webServiceUrl = \Yii::$app->params['ekp_knowledge_main_service_api_url'];
            $soapClient = new \SoapClient($webServiceUrl);

            $param = array('DhkGUID' => $dhkGuid, 'YsAmount' => $amount);
            $response = $soapClient->UpdateAccountHk($param);

            $result = $response->UpdateAccountHkResult;
            return $result;
        } catch (\SoapFault $sf) {
            return ErrorInfo::setAndReturn(-1, $sf->getMessage(), $sf->getMessage());
        } catch (Exception $ex) {
            return ErrorInfo::setAndReturn(-1, $ex->getMessage(), $ex->getMessage());
        }
    }

    /**
     * 更新商机系统的应收款信息
     * @param array $allReceivable 所有的应收款数组
     * @return bool
     */
    public function updateBusinessSystemReceivable($allReceivable = [])
    {
        $error_message = '更新商机应收款信息:' . json_encode($allReceivable);
        try {

            $webServiceUrl = \Yii::$app->params['contract_erp_business_service_api_url'];
            $soapClient = new \SoapClient($webServiceUrl);

            $param = array('s' => json_encode($allReceivable,JSON_UNESCAPED_UNICODE));
            //$param = array('s' => $allReceivable);
            $response = $soapClient->EditGathering($param);//返回值：整型  1：成功 0：失败
            if (intval($response->EditGatheringResult) == 1) {
                return true;
            } else {
                return false;
            }
        } catch (\SoapFault $sf) {
            \Yii::error($error_message . ',异常信息:' . $sf->getMessage());
            return ErrorInfo::setAndReturn(-1, $sf->getMessage(), $sf->getMessage());
        } catch (Exception $ex) {
            \Yii::error($error_message . ',异常信息:' . $ex->getMessage());
            return ErrorInfo::setAndReturn(-1, $ex->getMessage(), $ex->getMessage());
        }
    }

    public function updateProductInfos($productInfos = [])
    {
        $error_message = '更新产品交付信息:' . json_encode($productInfos);
        try {

            $webServiceUrl = \Yii::$app->params['contract_product_business_service_api_url'];
            $soapClient = new \SoapClient($webServiceUrl);

            $param = array('product_info' => json_encode($productInfos));

            $response = $soapClient->SynDeliveryProduct($param);//返回值：整型  1：成功 0：失败
            $result = $response->SynDeliveryProductResult;
            if ($result === "{\"result\":true,\"message\":null}") {
                return true;
            } else {
                return false;
            }
        } catch (\SoapFault $sf) {
            \Yii::error($error_message . ',异常信息:' . $sf->getMessage());
            return ErrorInfo::setAndReturn(-1, $sf->getMessage(), $sf->getMessage());
        } catch (Exception $ex) {
            \Yii::error($error_message . ',异常信息:' . $ex->getMessage());
            return ErrorInfo::setAndReturn(-1, $ex->getMessage(), $ex->getMessage());
        }
    }

    /**
     * 获取出库单列表
     */
    public function GetDeliveryList($curpage=1,$pagesize = 20,$keyword = '',$datatype = '',$datastatus = ''){
        try {
            $outDomain = \Yii::$app->params['out_storehouse'];
            $url = $outDomain . '/api/DeliveryCommon/GetDeliveryList?type=yl';
            $params = "&page=" . $curpage . "&page_size=" . $pagesize . "&keyword=" . $keyword . "&delivery_status=" . $datastatus . "&delivery_scene=" . $datatype;
            $url = $url . $params;
            $curl = new Curl();
            $data = $curl->get($url);
            $mydatta = json_decode($data);
            if ($mydatta->result) {
                return $this->getReturnResult($mydatta->userData->data,true,'');
            } else {
                return $this->getReturnResult([],false,$mydatta->message);
            }
        } catch (Exception $ex) {
            return $this->getReturnResult([],false,$ex->getMessage());
        }
    }

    /**
     * 获取出库单明细
     */
    public function GetDeliveryDetail($deliveryGuid = ''){
        try {
            if (empty($deliveryGuid)) {
                return $this->getReturnResult([],false,'出库单GUID不能为空!');
            }
            $outDomain = \Yii::$app->params['out_storehouse'];
            $url = $outDomain . '/api/DeliveryCommon/GetYlDeliveryDetail?type=yl';
            $params = "&delivery_guid=" . $deliveryGuid;
            $url = $url . $params;
            $curl = new Curl();
            $data = $curl->get($url);
            $mydatta = json_decode($data);
            if ($mydatta->result) {
                return $this->getReturnResult($mydatta->userData->data,true,'');
            } else {
                return $this->getReturnResult([],false,$mydatta->message);
            }
        } catch (Exception $ex) {
            return $this->getReturnResult([],false,$ex->getMessage());
        }
    }

    /**
     * 出库单状态跟新
     */
    public function UpdateDeliveryState($deliveryGuid = '',$status = 0){
        try {
            if (empty($deliveryGuid) || empty($status)) {
                return $this->getReturnResult([],false,'出库单GUID及状态不能为空!');
            }
            $outDomain = \Yii::$app->params['out_storehouse'];
            $url = $outDomain . '/api/DeliveryCommon/UpdateDeliveryState?type=yl';
            $params = "&delivery_guid=" . $deliveryGuid . "&status=" . $status;
            $url = $url . $params;
            $curl = new Curl();
            $data = $curl->get($url);
            $mydatta = json_decode($data);

            Yii::info(['out_storehouse_UpdateDeliveryState' => ['params' => $url, 'result' => $data]],'api_info');

            if ($mydatta->result) {
                return $this->getReturnResult($mydatta->userData,true,'');
            } else {
                return $this->getReturnResult([],false,$mydatta->message);
            }
        } catch (Exception $ex) {
            return $this->getReturnResult([],false,$ex->getMessage());
        }
    }

    /**
     * 回传操作记录
     */
    public function AddOpreationRecord($params){
        try {
            if (empty($params)) {
                return $this->getReturnResult([],false,'参数不嫩为空!');
            }
            $outDomain = \Yii::$app->params['out_storehouse'];
            $url = $outDomain . '/api/DeliveryCommon/AddOpreationRecord?type=yl';
            $curl = new Curl();
            $curl->setPostParams($params);
            $data = $curl->post($url);
            $mydatta = json_decode($data);
            Yii::info(['out_storehouse_AddOpreationRecord' => ['params' => serialize($params), 'result' => $data]],'api_info');
            if ($mydatta->result) {
                return $this->getReturnResult($mydatta->userData,true,'');
            } else {
                return $this->getReturnResult([],false,$mydatta->message);
            }
        } catch (Exception $ex) {
            return $this->getReturnResult([],false,$ex->getMessage());
        }
    }

    /**
     * 获取工作流记录
     */
    public function GetWorkflowProcessList($deliveryGuid){
        try {
            if (empty($deliveryGuid)) {
                return $this->getReturnResult([],false,'出库单GUID不能为空!');
            }
            $outDomain = \Yii::$app->params['out_storehouse'];
            $url = $outDomain . '/api/DeliveryCommon/GetWorkflowProcessList?type=yl&delivery_guid='.$deliveryGuid;
            $curl = new Curl();
            $data = $curl->get($url);
            $mydatta = json_decode($data);
            if ($mydatta->result) {
                return $this->getReturnResult($mydatta->userData->data,true,'');
            } else {
                return $this->getReturnResult([],false,$mydatta->message);
            }
        } catch (Exception $ex) {
            return $this->getReturnResult([],false,$ex->getMessage());
        }
    }

    public function GetTenantInfo($keyword,$platform){
        try {
            if (empty($keyword) || empty($keyword)) {
                return $this->getReturnResult([],false,'参数不允许为空');
            }
            $outDomain = \Yii::$app->params['tenant_center'];
            $url = $outDomain . 'tenant-info?keyword='.$keyword.'&platform='.$platform;
            $curl = new Curl();
            $data = $curl->post($url);
            $data = json_decode($data);

            return $this->getReturnResult($data->data,true,'');
        } catch (Exception $ex) {
            return $this->getReturnResult([],false,$ex->getMessage());
        }
    }

    /**
     * 添加租户
     */
    public function AddTenant($params){
        try {
            if (empty($params)) {
                return "参数不允许为空!";
            }
            $outDomain = \Yii::$app->params['tenant_center'];
            $url = $outDomain . 'tenant/add';
            $curl = new Curl();
            $curl->setPostParams($params);
            $data = $curl->post($url);
            $data = json_decode($data);

            Yii::info(['tenant_center_tenant_add' => ['params' => serialize($params), 'result' => $data]],'api_info');

            if ($data->success) {
                return $this->getReturnResult($data->tenant_id,$data->success,'');
            } else {
                return $this->getReturnResult([],$data->success,$data->errMsg);
            }
        } catch (Exception $ex) {
            return $this->getReturnResult([],false,$ex->getMessage());
        }
    }

    /**
     * 租户授权
     */
    public function AuthTenant($params){
        try {
            if (empty($params)) {
                return "参数不允许为空!";
            }
            $outDomain = \Yii::$app->params['tenant_center'];
            $url = $outDomain . 'tenant/auth';
            $curl = new Curl();
            $curl->setPostParams($params);
            $data = $curl->post($url);
            $data = json_decode($data, true);

            Yii::info(['tenant_center_tenant_auth' => ['params' => serialize($params), 'result' => serialize($data)]],'api_info');

            //success为空则全部失败,errMsg为空则全部成功,否则部分成功,输出errMsg中的错误合同信息
            if (empty($data['errMsg']) && empty($data['success'])) {
                return $this->getReturnResult([], false,'授权失败--'.$data);
            }
            if (empty($data['errMsg'])) {
                return $this->getReturnResult([], true,'');
            } else {
                $errMsg = '';
                foreach ($data['errMsg'] as $err) {
                    if (!empty($err['contract_code'])) {
                        $errMsg .= "【会签单号{$err['contract_code']}授权失败,原因：{$err['reason']}】";
                    } else {
                        //直属特批：无合同无会签
                        $errMsg .= "授权失败,原因：{$err['reason']}】";
                    }
                }
                return $this->getReturnResult($data, false,$errMsg);
            }

            /*if ($data->success) {
                return $this->getReturnResult([],$data->success,'');
            } else {
                return $this->getReturnResult([],$data->success,$data->errMsg);
            }*/
        } catch (Exception $ex) {
            return $this->getReturnResult([],false,$ex->getMessage());
        }
    }

    /**
     * 租户授权
     */
    public function EkpIncomeSync($params){
        try {
            if (empty($params)) {
                return "参数不允许为空!";
            }

            $webServiceUrl = \Yii::$app->params['contract_income_sync'];
            $soapClient = new \SoapClient($webServiceUrl);
            $newparams = array('SrInfoJson' => json_encode($params)) ;
            $response = $soapClient->CreateSrInfo($newparams);//返回值：整型  1：成功 0：失败
            $result = $response->CreateSrInfoResult;
            $data = json_decode($result);

            $this->InsertInterfaceLogs('收入项调整同步EKP',$webServiceUrl,'contract2third',$newparams,$result,'');
            if ($data->Success) {
                return $this->getReturnResult([],$data->Success,'');
            } else {
                return $this->getReturnResult([],$data->Success,"ekp接口收入项同步异常!");
            }
        } catch (Exception $ex) {
            return $this->getReturnResult([],false,$ex->getMessage());
        }
    }

    //插入接口操作日志
    private function InsertInterfaceLogs($businesstype,$url,$direction,$params,$result,$remark){
        try {
            $erplogs = new ErpInterfaceOperationLogs();
            $erplogs->log_id = StringHelper::uuid();
            $erplogs->businesstype = $businesstype;
            $erplogs->interface_url = $url;
            $erplogs->direction = $direction;
            $erplogs->params = json_encode($params);
            $erplogs->result = $result;
            $erplogs->remark = $remark;
            $erplogs->created_on = ConfigEntity::getDbNowDate();
            $erplogs->created_by = Yii::$app->user->getIdentity()->userguid;
            $erplogs->modified_on = ConfigEntity::getDbNowDate();
            $erplogs->modified_by = Yii::$app->user->getIdentity()->userguid;
            $erplogs->save();
            return true;
        }catch (\yii\base\Exception $ex){
            return false;
        }
    }

    /**
     * 获取租户授权使用情况
     */
    public function getAuthAppUseList($contractcode){
        try {
            if (empty($contractcode)) {
                return "合同code不允许为空!";
            }
            $config['AuthAppApiUrl'] = \Yii::$app->params['auth_app_use_list'];
            $kong_api_config = \Yii::$app->params['kong_api_config'];
            $kong_api_config['time'] = time();
            $params = array('contract_code'=>$contractcode);

            $data = JWTHelper::sendRequestToAuthApp($params,'get-auth-details',$config,$kong_api_config,'post');

            if ($data) {
                return $this->getReturnResult($data,true,'');
            } else {
                return $this->getReturnResult([],false,"产品使用情况接口数据获取失败!");
            }
        } catch (Exception $ex) {
            return $this->getReturnResult([],false,$ex->getMessage());
        }
    }

    public function getReportList(){
        $outDomain = \Yii::$app->params['report_url'];
        $url = $outDomain . 'get-standard-list?sysCode=ContractSystem';
        $curl = new Curl();
        $data = $curl->get($url);
        $data = json_decode($data);
        if ($data) {
            return $this->getReturnResult($data->items,true,'');
        } else {
            return $this->getReturnResult([],false,"报表接口调用失败!");
        }
    }

    public function getReportDetail($reportid){
        $outDomain = \Yii::$app->params['report_url'];
        $url = $outDomain . 'standard-view?id='.$reportid;
        $curl = new Curl();
        $data = $curl->get($url);

        if ($data) {
            return $this->getReturnResult($data,true,'');
        } else {
            return $this->getReturnResult([],false,"报表接口调用失败!");
        }
    }

    public function GetCaigouParam($companyname){
        $outDomain = \Yii::$app->params['cg_api_url'];
        $url = $outDomain . 'find-developer-by-name?name='.$companyname;
        $curl = new Curl();
        $data = $curl->get($url);

        if (empty($data) || $data == '[]') {
            return $this->getReturnResult([],false,"该企业未在采购平台注册!");
        } else {
            return $this->getReturnResult(json_decode($data),true,'');
        }
    }

    public function exportAccountHkList($paymentAccountName = ''){

        $objPHPExcel = new \PHPExcel();
        $data = $this->getAccountHkList($paymentAccountName);
        $activeSheet = self::getActiveSheet($objPHPExcel);
        $activeSheet->setTitle('合同');

        //设置单元格的值
        $activeSheet->setCellValue('A1', '财务编号');
        $activeSheet->setCellValue('B1', '付款客户'); // 新
        $activeSheet->setCellValue('C1', '到账金额');
        $activeSheet->setCellValue('D1', '到账时间');
        $activeSheet->setCellValue('E1', '款项所属公司');
        $activeSheet->setCellValue('F1', '已录入金额'); // 新
        $activeSheet->setCellValue('G1', '未录入回款');
        $activeSheet->setCellValue('H1', '备注');

        $activeSheet->getColumnDimension('A')->setWidth(20);
        $activeSheet->getColumnDimension('B')->setWidth(20);
        $activeSheet->getColumnDimension('C')->setWidth(20);
        $activeSheet->getColumnDimension('D')->setWidth(20);
        $activeSheet->getColumnDimension('E')->setWidth(20);
        $activeSheet->getColumnDimension('F')->setWidth(20);
        $activeSheet->getColumnDimension('G')->setWidth(20);
        $activeSheet->getColumnDimension('H')->setWidth(20);

        if (!empty($data)) {
            $j = 2;
            foreach ($data as $key => $val) {
                $i = 'A';
                $activeSheet->setCellValue($i . $j, $val['finance_code']); //财务编号
                $i++;
                $activeSheet->setCellValue($i . $j, $val['payment_account_name']); //付款客户
                $i++;
                $activeSheet->setCellValue($i . $j, $val['payment_amount']); //到账金额
                $i++;
                $activeSheet->setCellValue($i . $j, $val['payment_date']); //到账时间
                $i++;
                $activeSheet->setCellValue($i . $j, $val['KxBuName']); //款项所属公司
                $i++;
                $activeSheet->setCellValue($i . $j, $val['have_payment_amount']); //已录入金额
                $i++;
                $activeSheet->setCellValue($i . $j, $val['not_payment_amount']); //未录入回款
                $i++;
                $activeSheet->setCellValue($i . $j, $val['remark']); //备注
                $j++;
            }
        }

        $objWriter = new \PHPExcel_Writer_Excel5($objPHPExcel);
        ob_end_clean();
        header("Pragma: public");
        header("Expires: 0");
        header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
        header("Content-Type:application/force-download");
        header("Content-Type:application/vnd.ms-execl");
        header("Content-Type:application/octet-stream");
        header("Content-Type:application/download");

        header('Content-Disposition:attachment;filename="待录入回款' . date("YmdHis") . '.xls"');
        header("Content-Transfer-Encoding:binary");
        $objWriter->save('php://output');
        exit;

    }

    private static function getActiveSheet($objPHPExcel)
    {
        if (self::$sheetIndex == 0) {
            $objPHPExcel->setActiveSheetIndex(self::$sheetIndex);
            $activeSheet = $objPHPExcel->getActiveSheet();
        } else {
            $activeSheet = $objPHPExcel->createSheet(self::$sheetIndex);
        }
        self::$sheetIndex++;
        return $activeSheet;
    }

    /**
     * @param $userName
     * @return string
     */
    public static function getUserIdByName($userName){
        if(!$userName){
            return '';
        }
        $userId = ErpUserRepository::getUserGUIDByUserName($userName);
        return !empty($userId) ? $userId : '';
    }

}
